# This is a sample Python script.
from binance.um_futures import UMFutures
import time;
import requests
import datetime

url = 'https://kyb-api.520iy.com/public/sendWxMsg'


# user_amount  用户总份额 per_portion_val 每份价值
def send_msg(openid,one,two,diff):
    paras = {}
    paras['openid'] = openid
    msg = {}
    paras['msg'] = msg

    msg['type'] = 'income_msg'
    msg['one'] = one
    msg['two'] = two
    msg['diff'] = diff

    msg['time'] = ''
    # response = requests.post(url, json=paras)


def send_notification(symbol):
    """
    发送通知的方法，可以根据需要实现通知逻辑（邮件、短信、钉钉等）。
    """
    print(f"Notification: {symbol}")



def calculate_ema(data, window):
    """
    计算时间序列数据的指数移动平均值 (EMA)。

    参数:
    - data: list 或 numpy array, 时间序列数据。
    - window: int, EMA的时间窗口（平滑系数的基础）。

    返回:
    - ema: list, 计算后的 EMA 值。
    """
    if not data or len(data) < window:
        raise ValueError("数据长度必须大于时间窗口")

    alpha = 2 / (window + 1)  # EMA 平滑系数
    ema = [data[0]]  # 初始化第一个 EMA 值为第一个数据点

    for i in range(1, len(data)):
        ema_value = alpha * data[i] + (1 - alpha) * ema[-1]
        ema.append(ema_value)

    return ema

#type 1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,1M
def monitor_price(client: UMFutures, symbol, type):
    global start_time
    result = client.mark_price(symbol=symbol);
    markPrice = float(result['markPrice']);

    kline_data = client.klines(symbol=symbol, interval=type, limit=200);
    data = [];
    for item in kline_data:
        price = float(item[1]);
        data.append(price);
    ema_array = calculate_ema(data, 25)
    ema_price = ema_array[-1];
    print(f" mark price is {markPrice} for symbol: {symbol}");
    print(f" ema price is {ema_price} for symbol: {symbol} ");
    if markPrice < ema_price:
        # 标记价格低于
        msg_one = '合约:  {}   K线类型:{}'.format(symbol,type)
        msg_two = 'ema:  {}'.format(ema_price)
        msg_diff = '合约价格:  {}'.format(markPrice)
        send_msg('ocAr152-22tVKGt2Fp-E9GZ06Oos', one=msg_one, two=msg_two, diff=msg_diff)
        send_msg('ocAr157l0xBsK2-WVZKjuPn0rzfs', one=msg_one, two=msg_two, diff=msg_diff)
        send_msg('ocAr158EKzaSyrUH_D91DDq6ipxs', one=msg_one, two=msg_two, diff=msg_diff)
        send_msg('ocAr1534Q295U02-OvVaQDnsIsNY', one=msg_one, two=msg_two, diff=msg_diff)

        send_msg('ocAr15_V5VzRThpYYZCVg3aY0-As', one=msg_one, two=msg_two, diff=msg_diff)
        start_time = time.time()
        return True
    else:
        return False;


start_time = time.time()


# Press the green button in the gutter to run the script.

def main():
    um_futures_client = UMFutures()
    symbols = ["BTCUSDT", "ETHUSDT", "DOGEUSDT"]
    interval = "1m"
    notification_interval = 10  # 每10分钟触发一次检测（单位：秒）

    while True:

        # 在10分钟内多次运行 monitor_price
        notify_symbol = {};
        while time.time() - start_time > notification_interval:
        # while True:
            for symbol in symbols:
                if notify_symbol.__contains__(symbol):
                    continue;
                result = monitor_price(um_futures_client, symbol, interval)
                print("symbol :{}  result:{}".format(symbol,result))
                # if result:
                #     notify_symbol[symbol] = symbol;
                time.sleep(0.5);
            time.sleep(1)
              # 每隔2秒运行一次 monitor_price

        # 如果在这10分钟内触发了通知条件
        # for symbol in notify_symbol:
        #     send_notification(symbol);
        # notify_symbol.clear();
        time.sleep(1)

        print("Waiting for the next notification cycle...")

if __name__ == '__main__':
    #print('PyCharm')
    main();

# See PyCharm help at https://www.jetbrains.com/help/pycharm/
